<template>
  <div id="settingUp">
    <el-popover placement="top" width="570" v-model="visible" trigger="click">
      <el-transfer
        ref="transfer"
        id="transfer"
        target-order="unshift"
        filterable
        :filter-method="filterMethod"
        @left-check-change="checkedChange"
        filter-placeholder="请输入字段名查询"
        :titles="['隐藏字段', '显示字段']"
        v-model="value"
        :data="data"
      >
        <span
          slot-scope="{ option }"
          class="item"
          @dragstart="drag($event, option)"
          >{{ option.label }}</span
        >
      </el-transfer>
      <div style="text-align: right; margin: 0">
        <el-button size="mini" type="text" @click="visible = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="AddResultFn"
          >确定</el-button
        >
      </div>
      <el-button slot="reference"><i class="el-icon-setting"></i></el-button>
    </el-popover>
  </div>
</template>
<script>
import Sortable from "sortablejs";
import { dynamicHeaderCreate, dynamicHeaderUserList } from "@/api/waybill";
export default {
  name: "settingUp",
  props: ["settype", "objSettinUpdata"],
  data() {
    return {
      data: [],
      value: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
      visible: false,
    };
  },
  mounted() {
    this.dynamicHeaderListFn();
    const transfer = this.$refs.transfer.$el;
    const leftPanel = transfer
      .getElementsByClassName("el-transfer-panel")[0]
      .getElementsByClassName("el-transfer-panel__body")[0];
    const rightPanel = transfer
      .getElementsByClassName("el-transfer-panel")[1]
      .getElementsByClassName("el-transfer-panel__body")[0];
    const rightEl = rightPanel.getElementsByClassName(
      "el-transfer-panel__list"
    )[0];
    Sortable.create(rightEl, {
      animation: 100,
      onEnd: (evt) => {
        const { oldIndex, newIndex } = evt;
        const temp = this.value[oldIndex];
        if (!temp || temp === "undefined") {
          return;
        }
        for (var i = 0; i < this.value.length; i++) {
          if (
            this.value[i] === "" ||
            this.value[i] === null ||
            typeof this.value[i] === "undefined"
          ) {
            this.value.splice(i, 1);
            i = i - 1;
          }
        }
        const arr_temp = [].concat(this.value); // 创建一个新的临时数组，用以操作后不变更原数组
        // console.log(arr_temp, "移动之前");
        arr_temp.splice(newIndex, 0, arr_temp.splice(oldIndex, 1)[0]); // 在b位置插入从a位置截取的元素
        this.value = arr_temp;
        // console.log(this.value, "移动之后");
        this.$emit("update:call-back", this.value);
      },
    });
    const leftEl = leftPanel.getElementsByClassName(
      "el-transfer-panel__list"
    )[0];
    Sortable.create(leftEl, {
      animation: 100,
      onEnd: (evt) => {
        const { oldIndex, newIndex } = evt;
        const temp = this.datas[oldIndex];
        this.$set(this.datas, oldIndex, this.datas[newIndex]);
        this.$set(this.datas, newIndex, temp);
      },
    });
    leftPanel.ondragover = (ev) => {
      ev.preventDefault();
    };
    leftPanel.ondrop = (ev) => {
      ev.preventDefault();
      const index = this.value.indexOf(this.draggingKey);
      if (index !== -1) {
        this.value.splice(ev, 1);
      }
      // console.log(this.draggingKey, "draggingKey");
    };
    rightPanel.ondragover = (ev) => {
      ev.preventDefault();
    };
    rightPanel.ondrop = (ev) => {
      ev.preventDefault();
      if (this.value.indexOf(this.draggingKey) === -1) {
        this.value.push(this.draggingKey);
      }
    };
  },
  methods: {
    dynamicHeaderListFn() {
      this.dynamicHeaderUserListFn();
    },
    // 用户设定表头字段（显示字段）
    dynamicHeaderUserListFn() {
      let data = {
        header_id: this.settype + "",
      };
      dynamicHeaderUserList(data).then((res) => {
        if (res.code === 10000) {
          let showData = [];
          let idData = [];
          res.data.select_items == null
            ? []
            : res.data.select_items.forEach((val, index) => {
                showData.push({
                  label: val.title,
                  key: val.id,
                  pinyin: val.title,
                });
              });
          this.data = showData;
          res.data.un_selected_items == null
            ? []
            : res.data.un_selected_items.forEach((val, index) => {
                showData.push({
                  label: val.title,
                  key: val.id,
                  pinyin: val.title,
                });
              });
          this.data = showData;
          res.data.select_items == null
            ? []
            : res.data.select_items.forEach((val, index) => {
                idData.push(val.id);
              });
          this.value = idData;
        }
      });
    },
    checkedChange() {
      this.objSettinUpdata();
    },
    AddResultFn() {
      this.visible = false;
      let rightData;
      rightData = this.data.filter((item) => this.value.includes(item.key));
      let arritemsdata = rightData.map((element, index) => {
        return {
          id: element.key + "",
          sequence: rightData.length - this.value.indexOf(element.key) + "",
        };
      });

      let dataObj = {
        header_id: this.settype + "",
        items_data: arritemsdata,
      };
      dynamicHeaderCreate(dataObj).then((res) => {
        if (res.code === 10000) {
          this.visible = false;
          this.dynamicHeaderUserListFn();
          this.checkedChange();
        }
      });
    },
  },
};
</script>
<style scoped lang="less">
</style>